package com.kly.aop;

import com.kly.annotation.AuthCheck;
import com.kly.domain.entity.User;
import com.kly.domain.enums.UserRoleEnum;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import com.kly.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author admin
 * @date 2025/3/2
 */
@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    @Pointcut("execution(* com.kly.controller.*.*(..))")
    private void pc() {}

    @Around("pc() && @annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        // 获取request
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 获取注解中的角色要求
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        // 无权限要求
        if(mustRoleEnum == null) {
            return joinPoint.proceed();
        }

        // 需要权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        // 没有权限拒绝
        ThrowUtils.throwIf(userRoleEnum == null, ErrorCode.NO_AUTH_ERROR);
        // 需要管理员权限 但没有
        ThrowUtils.throwIf(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum), ErrorCode.NO_AUTH_ERROR);
        // 权限符合，放行
        return joinPoint.proceed();
    }
}
